package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SaveOrderStrategyContext  implements ApplicationContextAware {

    // 在该Map中存储所有的策略对象
    private static final Map<String , SaveOrderStrategy> SAVE_ORDER_STRATEGY_MAP = new HashMap<>() ;

    public static SaveOrderStrategy getSaveOrderStrategy(String payWay) {
        return SAVE_ORDER_STRATEGY_MAP.get(payWay) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, SaveOrderStrategy> beansOfType = applicationContext.getBeansOfType(SaveOrderStrategy.class);
        beansOfType.values().stream().forEach( saveOrderStrategy -> {
            String payWay = saveOrderStrategy.getPayWay();
            SAVE_ORDER_STRATEGY_MAP.put(payWay , saveOrderStrategy) ;
        });
    }
}
